import numpy as np
import pandas as pd

def __GRA_ONE(DataFrame, m=0):
    gray = DataFrame
    # 读取为df格式
    gray = (gray - gray.min()) / (gray.max() - gray.min())
    # 标准化
    std = gray.iloc[:, m]  # 为标准要素
    ce = gray.iloc[:, 0:]  # 为比较要素
    n = ce.shape[0]
    m = ce.shape[1]  # 计算行列
    # print(std,ce,n,m)
    # 与标准要素比较，相减
    a = np.zeros([m, n])
    for i in range(m):
        for j in range(n):
            a[i, j] = abs(ce.iloc[j, i] - std[j])
    # 取出矩阵中最大值与最小值
    c = np.amax(a)
    d = np.amin(a)
    # 计算值
    result = np.zeros([m, n])
    for i in range(m):
        for j in range(n):
            if a[i, j] + 0.5 * c == 0:
                result[i, j] = np.NaN
            else:
                result[i, j] = (d + 0.5 * c) / (a[i, j] + 0.5 * c)
    # 求均值，得到灰色关联值
    result2 = np.zeros(m)
    for i in range(m):
        result2[i] = np.mean(result[i, :])
    return pd.DataFrame(result2)


def gra_df(DataFrame):
    list_columns = [DataFrame.columns[i] for i in range(len(DataFrame.columns))]
    df_local = pd.DataFrame(columns=list_columns)
    for i in range(len(DataFrame.columns)):
        df_local[df_local.columns[i]] = __GRA_ONE(DataFrame, m=i)[0]
    return df_local